import React, { useRef, useEffect } from 'react';
import getCssPrefix from '@root/lib/getCssPrefix';
import getScrollBarSize from '@root/lib/getScrollBarSize';
import scrollSync from '../lib/scrollSync';
import detectScrollToEdge from './lib/detectScrollToEdge';
import useGenStyle from './hooks/useGenStyle';
const { cssPrefix } = getCssPrefix();
const { size: scrollSize } = getScrollBarSize();
const scrollId = 'scrollBar';
function BaseScrollBar(props) {
    const { width, main, setBarVisible, modifyState, scrollUtility } = props;
    const barRef = useRef(null);
    const contentRef = useRef(null);
    const ignoreScrollRef = useRef(null);
    const { contentStyle, barStyle } = useGenStyle(main, width, scrollSize);
    useEffect(() => {
        if (main) {
            /* 注册scroll的同步函数 */
            scrollUtility.register(scrollId, function (v) {
                ignoreScrollRef.current = true;
                barRef.current.scrollLeft = v;
            });
            /* 监听scroll事件 */
            scrollSync(barRef.current, (v) => {
                modifyState('scrollToLeft', detectScrollToEdge(barRef.current, 'left'));
                modifyState('scrollToRight', detectScrollToEdge(barRef.current, 'right'));
                let ignore = ignoreScrollRef.current;
                ignoreScrollRef.current = false;
                if (ignore) return;
                typeof scrollUtility.scroll === 'function' && scrollUtility.scroll(scrollId, v);
            });
            /* 监听dom的size发生变化的事件 */
            const resizeObserver = new ResizeObserver(() => {
                let outWidth = barRef.current.offsetWidth;
                let innerWidth = contentRef.current.offsetWidth;
                typeof setBarVisible === 'function' && setBarVisible(outWidth < innerWidth);
                modifyState('scrollToLeft', detectScrollToEdge(barRef.current, 'left'));
                modifyState('scrollToRight', detectScrollToEdge(barRef.current, 'right'));
            })
            resizeObserver.observe(barRef.current);
            resizeObserver.observe(contentRef.current);
            /* 销毁size变化事件 */
            return function () {
                resizeObserver.disconnect();
            }
        }
    }, []);
    return (
        <div ref={barRef} className={`${cssPrefix}-base-scroll-bar`} style={barStyle}>
            <div ref={contentRef} style={contentStyle}></div>
        </div>
    );
}
export default BaseScrollBar;